<?php
/**
 *
 * @author 凡墙<jihaoju@qq.com>
 * @date 2018/7/13 15:01
 * @description
 */

namespace apps\marriage\core\service;


use apps\marriage\core\model\UserPlatform;
use vm\com\BaseModel;
use vm\com\BaseService;

class UserPlatformService extends BaseService
{

    /**
     * @return UserPlatform|BaseModel
     */
    protected function getModel()
    {
        return new UserPlatform();
    }

    public function getByOpenid($openid)
    {
        return $this->info([
            'open_id' => $openid
        ]);
    }

    public function getByUnionid($unionid)
    {
        return $this->getAll([
            'union_id' => $unionid
        ]);
    }

    public function getByUserId($userId)
    {
        return $this->getAll([
            'user_id' => $userId
        ]);
    }

    public function getByUserIdWithAppid($appid, $userId)
    {
        return $this->info([
            'appid' => $appid,
            'user_id' => $userId
        ]);
    }

    public function save(array $data)
    {
        if($data['id'] == 0) {
            return $this->create($data);
        } else {
            return $this->updateByPk($data);
        }
    }

    /**
     * 验证用户是否已关注公众号
     * @param $userId
     * @return bool
     * @throws \think\Exception
     */
    public function checkUserSubscribedMpAccount($userId)
    {
        if($this->info([
            'user_id' => $userId,
            'platform' => UserPlatform::PLATFORM_WX_MP,
            'is_subscribed' => 1
        ])) {
            return true;
        }

        $platforms = $this->getByUserId($userId);
        foreach ($platforms as $platform) {
            if(!empty($platform['union_id']) && $this->info([
                    'union_id' => $platform['union_id'],
                    'platform' => UserPlatform::PLATFORM_WX_MP,
                    'is_subscribed' => 1
                ])) {
                return true;
            } else if($this->info([
                'open_id' => $platform['open_id'],
                'platform' => UserPlatform::PLATFORM_WX_MP,
                'is_subscribed' => 1
            ])) {
                return true;
            }
        }

        return false;
    }
}